package com.library.servlet;

import com.library.util.DBUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/mySubscriptions")
public class MySubscriptionsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonResponse = new JSONObject();
        JSONArray booksArray = new JSONArray();

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "请先登录");
            response.getWriter().write(jsonResponse.toString());
            return;
        }
        int userId = (int) session.getAttribute("userId");

        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT b.id, b.title, b.author, b.isbn, br.id as borrowId, br.due_date " +
                         "FROM books b JOIN borrow_records br ON b.id = br.book_id " +
                         "WHERE br.user_id = ? AND br.status = 'borrowed'";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setInt(1, userId);
                try (ResultSet rs = stmt.executeQuery()) {
                    while (rs.next()) {
                        JSONObject book = new JSONObject();
                        book.put("id", rs.getInt("id"));
                        book.put("title", rs.getString("title"));
                        book.put("author", rs.getString("author"));
                        book.put("isbn", rs.getString("isbn"));
                        book.put("borrowId", rs.getInt("borrowId"));
                        book.put("dueDate", rs.getString("due_date"));
                        booksArray.put(book);
                    }
                }
            }
            jsonResponse.put("success", true);
            jsonResponse.put("books", booksArray);
        } catch (SQLException e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "系统错误");
        }
        response.getWriter().write(jsonResponse.toString());
    }
}